/*
 * Copyright 2014 Graham Smith
 */
package uk.co.wobblycogs.vegas.scan;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.sql.ResultSet;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import uk.co.wobblycogs.vegas.scan.FileFinder;
import uk.co.wobblycogs.vegas.scan.ScanResults;

/**
 *
 * @author Graham Smith
 */
public class MediaFinder extends FileFinder {

	private static final String DEFAULT_GLOB_PATTERN = "*.{mp4,mts,m2ts}";
	private final FileResourceService frs = new FileResourceService();

	public MediaFinder() {
		this(DEFAULT_GLOB_PATTERN);
	}

	public MediaFinder(String pattern) {
		super(pattern);
	}

	@Override
	public void process(Path file) throws IOException {
		FileResource r = frs.findByPath(file);
		if (r == null) {
			logger.debug("Adding: {}", file.toString());
			r = new FileResource(file);
			r.setLastModified(Files.getLastModifiedTime(file));
			r.setFileSize(Files.size(file));
			r.setExtension(FilenameUtils.getExtension(file.toString()));
			frs.persist(r);
		} else {
			logger.debug("Updating: {}", file.toString());
			//Only update the entry if the last modified has changed or the size has
			//changed. Size is useful as last modified can be reset by applications.
			FileTime lastModified = Files.getLastModifiedTime(file);
			Long size = Files.size(file);
			if (!lastModified.equals(r.getLastModified()) || !size.equals(r.getFileSize())) {
				r.setLastModified(lastModified);
				r.setFileSize(size);
				frs.merge(r);
			}
		}
	}

}
